import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useContext, useEffect, useState } from 'react';
import { ChangeControllerContext } from '../common/useOAContext';
import { Form, Input, Select, Spin, Switch, Tooltip, TreeSelect, message, Button } from 'antd';
import { useDescriptions, Descriptions } from '@/components/Descriptions';
import pageStyles from '@/common/pageLayout.less';
import { downloadTemplate, getFileNameNotType, getLoadMapList, getTenantID, splitFileUrl } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import MyIcon from '@/components/MyIcon';
import { formatDecimal } from '../../Acommon';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { RegularExpression } from '@/common/constVariable';
import { getFlowOrgTreeByOrgIDService, getUserDataList } from '@/services/BaseLayout';
import DetailInfoTableList from './DetailInfoTableList';
import DetailInfoServiceTableList from './DetailInfoServiceTableList';
import { TypographyTitle } from '@/components/Typography/TypographyTitle';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

export const DetailInfoCenterViewMainOA: React.FC = () => {
  /** 引入上下文 */
  const { styleFixCls, infoObj } = useContext(ChangeControllerContext);

  const [isPass, setIsPass] = useState<boolean>(false); // 是否通过线下审批

  /**  获取数据字典 */
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_TYPE}`, //资产类型
    `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`, //折旧方式
    `${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`, //资产来源
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_BRAND}`, //资产品牌
    `${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`, //资产存放地点
    `${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`, //量化单位
  ]);

  const [changeFromRef] = Form.useForm(); // 表单实例

  /** 获取组织机构树接口 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    /** 初始化请求组织机构 */
    let payload = {
      params: '0',
      flowType: '0',
    };
    getFlowOrgTreeRun(payload);
    if (infoObj?.id) {
      getUserRun({
        //获取当前部门用户信息
        userDepartmentID: infoObj?.useDepartmentID,
      });
      BasicMethods?.setFieldsValue({
        ...infoObj,
        expectSum: formatDecimal(infoObj?.expectSum),
      });
      ReMethods?.setFieldsValue({
        ...infoObj,
        expectSum: formatDecimal(infoObj?.expectSum),
      });
    }
  }, [infoObj]);

  // 表格表单配置信息
  const [config, BasicMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        field: `createTime`,
        label: `申请日期`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
      {
        field: `applyCode`,
        label: `流水单号`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带入',
        required: false,
      },
      {
        field: `createrName`,
        label: `申请人`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
      {
        field: `createPhone`,
        label: `联系电话`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
      {
        field: `createDepartmentName`,
        label: `申请部门/单位`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
      {
        field: `createPositionName`,
        label: `职务岗位`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
    ],
  });

  // 表格表单配置信息
  const [ReConfig, ReMethods] = useDescriptions({
    labelWidth: 200,
    basicForm: changeFromRef,
    schemas: [
      {
        field: `oto`,
        label: `验收方式`,
        component: 'Render',
        required: false,
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return infoObj.oto === 0 ? '线上验收' : infoObj.oto === 1 ? '线下验收' : '--';
        },
      },
      {
        field: `applyTitle`,
        label: `事项名称`,
        component: 'Input',
        disabled: true,
        placeholder: '自动带出',
        autoComplete: 'off',
        required: false,
      },
      {
        field: `purchaseApplyName`,
        label: `采购申请`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
      {
        field: `contractName`,
        label: `采购合同`,
        component: 'Input',
        disabled: true,
        required: false,
        placeholder: '自动带出',
      },
      {
        field: `contractProcessName`,
        label: `履约节点`,
        component: 'Render',
        disabled: true,
        required: false,
        placeholder: '自动带出',
        render: (text) => {
          return text ? text : '--';
        },
      },
      {
        field: `fileAll`,
        label: `文件资料是否齐全`,
        component: 'Render',
        required: false,
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return <Switch checkedChildren="是" unCheckedChildren="否" onChange={(value) => {}} disabled={true} checked={Boolean(text)} />;
        },
      },
      {
        field: `storageType`,
        label: `验收类型`,
        component: 'Render',
        required: false,
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return infoObj.storageType === 1 ? '货物类' : infoObj.storageType === 2 ? '服务类' : infoObj.storageType === 3 ? '货物类&服务类' : '--';
        },
      },
      {
        field: `matarialAll`,
        label: `备品备件是否齐全`,
        component: 'Render',
        required: false,
        disabled: true,
        placeholder: '自动带出',
        render: (text) => {
          return <Switch checkedChildren="是" unCheckedChildren="否" onChange={(value) => {}} disabled={true} checked={Boolean(text)} />;
        },
      },
      {
        field: `checkFlag`,
        label: `收货检验`,
        component: 'Render',
        required: false,
        disabled: true,
        placeholder: '自动带出',
        colSpan: 2,
        render: (text) => {
          return infoObj.storageType === 0 ? '合格' : infoObj.storageType === 1 ? '存在一般问题，经现场处理解决' : '--';
        },
      },
      {
        field: `otherInfo`,
        label: `其他说明`,
        component: 'InputTextArea',
        disabled: true,
        required: false,
        colSpan: 2,
        allowClear: true,
        showCount: true,
        render: (text) => {
          if (text) {
            return <Input.TextArea disabled value={text} showCount maxLength={200} autoSize={{ minRows: 2, maxRows: 4 }} />;
          } else {
            return (
              <div
                style={{
                  height: '100%',
                  display: 'flex',
                  alignItems: 'center',
                  marginLeft: '8px',
                }}
              >
                --
              </div>
            );
          }
        },
      },
      {
        field: `applyFile`,
        label: `相关附件`,
        component: 'Render',
        required: false,
        placeholder: '请上传',
        render: (text, record) => {
          const fileName = 'applyFile';
          return (
            <div
              style={{
                height: '100%',
                display: 'flex',
                alignItems: 'center',
                marginLeft: '8px',
              }}
            >
              {record?.[fileName]
                ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                    return (
                      <div>
                        <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                          <a
                            onClick={() => {
                              message.success('下载中，请稍后...');
                              downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                            }}
                          >
                            <MyIcon type="icon-file-text-fill" />
                            &nbsp;
                            {getFileNameNotType(e.attachName, 8)}
                          </a>
                        </Tooltip>
                        {/* 轻阅读预览 */}
                        <Tooltip title={'在线预览'}>
                          <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                        </Tooltip>
                      </div>
                    );
                  })
                : '--'}
            </div>
          );
        },
      },
    ],
  });

  return (
    <>
      <div className="commonTabsBodyDom">
        <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
          <ScrollBarLayout style={{ padding: '20px 10%' }}>
            <Spin spinning={mapLoading}>
              <TypographyTitle children={'到货验收申请'} style={{ textAlign: 'center', borderLeft: 'none' }} level={1} />
              <TypographyTitle children={'基本信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={config} />

              <TypographyTitle children={'到货验收信息'} style={{ margin: '25px 0px 20px' }} level={2} />
              <Descriptions config={ReConfig} />

              {/* 货物列表 */}
              {infoObj?.massetApplyNumberList?.length > 0 && (
                <>
                  {/* <div className={'apply-update-title-divClassName'}>{infoObj.storageType === 3 || infoObj.storageType === 1 ? '二、货物' : ''}</div> */}

                  {(infoObj.storageType === 3 || infoObj.storageType === 1) && (
                    <TypographyTitle children={'货物'} style={{ margin: '25px 0px 20px' }} level={2} />
                  )}
                  <DetailInfoTableList dataList={infoObj?.massetApplyNumberList || []} />
                </>
              )}

              {/* 服务列表 */}
              {infoObj?.massetApplyNumberList?.length > 0 && (
                <>
                  {/* <div className={'apply-update-title-divClassName'}>
                    {infoObj.storageType === 3 || infoObj.storageType === 2 ? (infoObj.storageType === 2 ? '二、服务' : '三、服务') : ''}
                  </div> */}

                  {(infoObj.storageType === 3 || infoObj.storageType === 1) && (
                    <TypographyTitle children={'服务'} style={{ margin: '25px 0px 20px' }} level={2} />
                  )}
                  <DetailInfoServiceTableList dataList={infoObj?.massetApplyNumberList || []} />
                </>
              )}
            </Spin>
          </ScrollBarLayout>
        </div>
      </div>
    </>
  );
};
